package L_5_8.demo3;


class Money implements Cloneable {
    public int money = 10;

    @Override
    protected Object clone () throws CloneNotSupportedException {
        return super.clone ();
    }


}


class person implements Cloneable {
    public int age;
    public String name;
    public Money m;

    public person (int age, String name) {
        this.age = age;
        this.name = name;
        //构造方法对money进行初始化
        this.m = new Money ();
    }

    @Override
    protected Object clone () throws CloneNotSupportedException {
        //
        person temp = (person) super.clone ();
        temp.m = (Money) this.m.clone ();
        return temp;
    }

    @Override
    public String toString () {
        return "person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

public class test {

    public static void main (String[] args) throws CloneNotSupportedException {
        person p1 = new person (10, "hong");
        person p2 = new person (20, "huang");

        //clone方法的返回值是Object类，用person接收需要用到强制类型转换

        person p3 = (person) p1.clone ();
        p1.m.money = 20;
        //不对clone方法重写时，得到的是浅拷贝

        System.out.println (p1.m.money);
        System.out.println (p3.m.money);
    }
}
